import userStore from '@/store/user'
// const baseUrl = "https://longapp.top"
// const baseUrl = "http://139.196.24.241:8848"
const baseUrl = "http://localhost:8848"

export interface BaseResponse<T> {
  code: number
  data: T
  msg: string
  token?: string
}
export interface BasePageResponse<T> {
  records: T[],
  total: number,
  size: number,
  current: number,
  orders: string[],
  optimizeCountSql: boolean,
  searchCount: boolean,
  countId: string | null,
  maxLimit: number | null,
  pages: number
}

const fnReplaceUrl = (url: string, repObj: any) => {
  let newUrl = String(url)
  if (repObj instanceof Object) {
    Object.keys(repObj).forEach((item) => {
      let repIStr
      console.log("item", isEmpty(repObj[item]))
      if(isEmpty(repObj[item])) return
      if (Array.isArray(repObj[item]))
        repIStr = repObj[item].join(',')
      else
        repIStr = repObj[item].toString()
      newUrl = newUrl.replace(`{${item}}`, repIStr)
    })
  }
  return newUrl
}

interface FetchOption<DataT, RepObjT = unknown> {
  noToken?: boolean
  data?: DataT
  repObj?: RepObjT
  options?: any
  header?: any
}
function isEmpty(value: any){
  if(Array.isArray(value)){
    return value.length === 0
  }else if(typeof value === 'string'){
    return value !== '' && !value
  }else if(typeof value === 'number'){
    return value !== 0 && !value
  }else{
    return !value
  }
}
function filterData(param: Object){
  const newParam: any = {}
  Object.keys(param).forEach(item => {
    // @ts-ignore
    if (!isEmpty(param[item])) {
      // @ts-ignore
      newParam[item] = param[item]
    }
  })
  return newParam
}
type MethodType = 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'
export default <DataT = unknown, RepObjT = unknown, ResData = unknown>(url: string, method: MethodType, opt?: FetchOption<DataT, RepObjT>): Promise<BaseResponse<ResData>> => {
  const user = userStore()
  // @ts-ignore
  return new Promise((resolve, reject) => {
    const success = (res: UniNamespace.RequestSuccessCallbackResult) => {
      const data = res.data as BaseResponse<ResData>
      if(data && data.code === 200){
        resolve(res.data as BaseResponse<ResData>)
      }else {
        uni.showToast({title: data?.msg || '服务器出错了', icon: 'none'})
        reject(data)
      }
    }
    const fail = (res: UniNamespace.GeneralCallbackResult) => {
      reject({msg: res.errMsg, data: null, code: 500})
    }
    const options: UniNamespace.RequestOptions = {
      url: baseUrl + url,
      method: method,
      timeout: 3000,
      success,
      fail
    }
    if (opt?.header)
      options.header = opt.header
    if(opt?.data)
      options.data = filterData(opt.data)
    if (!opt?.noToken) {
      if (!user.token) {
        console.warn("未登录")
        // 未登录，需要让用户进行登录操作
        return uni.showToast({title: '未登录'})
      }
      if (!options.header)
        options.header = {}
      options.header.token = user.token
    }
    if (opt?.repObj) {
      options.url = fnReplaceUrl(options.url, opt.repObj)
    }
    uni.request(options)
  })
}
